package cn.xuchunh.campusbbs.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.NavigationView.OnNavigationItemSelectedListener;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.base.BaseActivity;
import cn.xuchunh.campusbbs.base.BaseFragment;
import cn.xuchunh.campusbbs.ui.fragments.CommunityFragment;
import cn.xuchunh.campusbbs.ui.fragments.DiscoverFragment;
import cn.xuchunh.campusbbs.ui.fragments.HomePageFragment;
import cn.xuchunh.campusbbs.ui.fragments.MessagesFragment;
import cn.xuchunh.campusbbs.ui.fragments.PersonFragment;
import cn.xuchunh.campusbbs.utils.Action;
import cn.xuchunh.campusbbs.utils.AppUtil;
import cn.xuchunh.campusbbs.utils.IntentParamsKey;

/**
 *
 * Created by XuChunH on 2015/10/8.
 */
public class DrawerMainActivity extends BaseActivity implements View.OnClickListener{

    private SearchView searchView;
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private BaseFragment homeFragment;
    private BaseFragment forumFragment;
    private BaseFragment messageFragment;
    private BaseFragment discoverFragment;
    private BaseFragment personFragment;
    private ActionBarDrawerToggle drawerToggle;

    public static void launch(Context context) {
        Intent intent = new Intent(context, DrawerMainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int createContentRes() {
        return R.layout.activity_main_drawer;
    }

    @Override
    protected void initView(View view) {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        navigationView = (NavigationView) findViewById(R.id.navigation);
        View headerView = navigationView.inflateHeaderView(R.layout.layout_navigation_header);
        ((SimpleDraweeView) headerView.findViewById(R.id.navigation_header_avatar))
                .setImageURI(Uri.parse(getUser().getAvatar()));
        headerView.findViewById(R.id.navigation_header_avatar).setOnClickListener(this);
        ((TextView) headerView.findViewById(R.id.navigation_header_user_name))
                .setText(getUser().getUserName());
        headerView.findViewById(R.id.navigation_header_container)
                .setBackgroundDrawable(AppUtil.getMaterialBanner(this));
        navigationView.setNavigationItemSelectedListener(new OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                navigate(menuItem);
                return false;
            }
        });
        navigationView.getMenu().findItem(R.id.menu_drawer_home).setChecked(true);
        homeFragment = new HomePageFragment();
        forumFragment = new CommunityFragment();
        messageFragment = new MessagesFragment();
        discoverFragment = new DiscoverFragment();
        personFragment = PersonFragment.newInstance(getUser().getUserId());

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container, homeFragment, HomePageFragment.class.getSimpleName());
        ft.commit();
    }

    @Override
    protected void beforeInitView() {
        setShowHomeUp(true);
    }

    @SuppressWarnings("ConstantConditions")
    @Override
    protected void afterInitView() {
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
                getToolbar(), R.string.confirm, R.string.cancel);
        drawerLayout.setDrawerListener(drawerToggle);
        ViewCompat.setElevation(getToolbar(), 0);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_main, menu);
        final MenuItem menuItem = menu.findItem(R.id.menu_main_search);
        searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQueryHint(getString(R.string.search_hint));
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!TextUtils.isEmpty(query)) {
                    Intent intent = new Intent();
                    intent.setAction(Action.SEARCH);
                    intent.putExtra(IntentParamsKey.SEARCH_QUERY, query);
                    searchView.clearFocus();
                    menuItem.collapseActionView();
                    startActivity(intent);
                    return true;
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return true;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    @Override
    protected void onStop() {
//        if(drawerLayout.isDrawerVisible(Gravity.LEFT)){
//            drawerLayout.closeDrawer(Gravity.LEFT);
//        }
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.closeDrawers();
        } else {
            super.onBackPressed();
        }
    }

    private void navigate(MenuItem menuItem) {
        int groupId = menuItem.getGroupId();
        if(groupId == R.id.menu_drawer_group_main){
            homePageNavigation(menuItem);
        }else {
            otherPageNavigation(menuItem);
        }

    }

    private void homePageNavigation(MenuItem menuItem){
        drawerLayout.closeDrawers();
        switch (menuItem.getItemId()) {
            case R.id.menu_drawer_home:
                showFragment(homeFragment);
                navigationView.getMenu().findItem(R.id.menu_drawer_home).setChecked(true);
                break;
            case R.id.menu_drawer_forum:
                showFragment(forumFragment);
                navigationView.getMenu().findItem(R.id.menu_drawer_forum).setChecked(true);

                break;
            case R.id.menu_drawer_find:
                showFragment(discoverFragment);
                navigationView.getMenu().findItem(R.id.menu_drawer_find).setChecked(true);

                break;
            case R.id.menu_drawer_message:
                showFragment(messageFragment);
                navigationView.getMenu().findItem(R.id.menu_drawer_message).setChecked(true);

                break;
            case R.id.menu_drawer_person:
                showFragment(personFragment);
                navigationView.getMenu().findItem(R.id.menu_drawer_person).setChecked(true);

                break;
            default:
                break;
        }
        if (menuItem.getItemId() == R.id.menu_drawer_home) {
            ViewCompat.setElevation(getToolbar(), 0);
        } else {
            ViewCompat.setElevation(getToolbar(), getResources().getDimensionPixelSize(R.dimen.elevation));
        }
    }

    private void otherPageNavigation(MenuItem menuItem){
        if(menuItem.getItemId() == R.id.menu_drawer_setting){
            SettingActivity.launch(this);
        }
    }

    private void showFragment(BaseFragment baseFragment) {
        if (baseFragment != null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            if (baseFragment.isAdded()) {
                ft.show(baseFragment);
            } else {
                ft.replace(R.id.container, baseFragment, baseFragment.getClass().getSimpleName());
            }
            ft.commit();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            drawerLayout.openDrawer(GravityCompat.START);
            return true;
        } else if (item.getItemId() == R.id.configuration) {
            SettingActivity.launch(this);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.navigation_header_avatar){
            UserActivity.launch(this, getUser().getUserId());
        }
    }
}
